package com.uduemc.biso.node.web.api.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.core.entities.custom.LoginUser;
import com.uduemc.biso.node.web.api.service.LoginService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api")
@Api(tags = "登录、用户管理模块")
public class LoginController {

	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private LoginService loginServiceImpl;

	@PostMapping("/login")
	@ApiOperation(value = "登录", notes = "登录 login")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "token", value = "主控端带过来的令牌", required = true, dataType = "string", paramType = "query", defaultValue = "2") })
	public JsonResult login(@RequestParam("token") String token) {
		logger.info("登录获取到的token: " + token);
		if (!StringUtils.hasText(token)) {
			return JsonResult.noLogin();
		}

		return loginServiceImpl.tokenLogin(token);
	}

	@PostMapping("/user/logout")
	public JsonResult logout() {
		loginServiceImpl.tokenLogout();
		return JsonResult.ok(1);
	}

	@PostMapping("/user")
	public JsonResult user() throws InterruptedException {
		LoginUser loginUser = loginServiceImpl.getLoginUser();
		if (loginUser == null) {
			return JsonResult.noLogin();
		}
		return JsonResult.ok(loginUser);
	}
}
